Central Article

Creating a Two-Way Video Chat Application in Macromedia Central

Giacomo Guilizzoni

Macromedia

The most exciting feature of Central, to me, is its notification mechanism. Finally you can build an application that sits in the background and attracts the user's attention only when necessary. I have been working on Flash Communication Server-powered applications for some time and I couldn't wait for this feature. A whole new set of instant messenger (IM)-style applications are now possible. Just combine Central and Flash Communication Server—the sky's the limit!

Instead of building a full-fledged IM application (I'm sure someone else is already working on it), I'll give you a little taste of what's possible when you combine a little Central code with a dash of good old-fashioned Flash Communication Server code.

Requirements

To get the most out of this tutorial you need to be comfortable developing Flash applications and familiar with Flash Communication Server concepts such as NetStreams, shared objects, and application instances. If you have never built a Flash Communication Server application before, download the documentation and come back here only after you've read "Developing Communication Applications" from start to finish.

You should also install the Central SDK and be somewhat familiar with developing Central applications. I won't be covering deployment of the two-way video chat application. Please refer to the Central SDK documentation for more information on how to distribute your Central applications.

To complete this tutorial you will need to install the following software and files:

Macromedia Central

Install Central now (free) ›

Macromedia Central SDK

Download it now ›

Macromedia Flash MX 2004


Macromedia Flash Communication Server MX 1.5


Tutorials and sample files:


The vChat Application

In this tutorial I show you how to create an application that allows multiple people to log on to a "room" and see who's online. They can click on a user's name and engage in a one-on-one audio/video conversation with them. The whole thing happens within a pod; the application functions as a help page (see Figure 1).

The vChat application shows users a quick overview of the different forms that compose it (login, user list, and video chat)

Figure 1. The vChat application shows users a quick overview of the different forms that compose it (login, user list, and video chat)

The Server-Side Code

When I build a Flash Communication Server application, I always start on the server side. It's much easier and it helps you think about how your application is going to work. Since vChat is such a simple application, a simple users shared object suffices. All you need to do is assign a unique ID to each user who connects, use that ID as the name of the slot in the shared object, and keep a simple object in the slot. The object contains the user's chosen username and a talkingTo pointer, which is null if the user is not talking to anyone but contains the ID of the user they're talking to when they're having a video chat.

Here's all the server-side code you need:

application.onAppStart = function()
{ 
   //Get a hold of the users Shared Object
   this.users_so = SharedObject.get("users",false);
}

application.onConnect = function(client, name)
{
   //find next available ID
   var i = 0;
   var tempObj = this.users_so.getProperty("u"+i);
   while (tempObj != null) {
      i++;
      tempObj = this.users_so.getProperty("u"+i);
   }
   //Save the ID in the client object
   client.id = "u"+i;

   //Add user to SO (this will trigger an onSync on the clients)
   this.users_so.setProperty(client.id, {name: name, talkingTo:null});

   //Accept this user's connection
   application.acceptConnection(client);

   //Tell this client what their ID is
   client.call("setID", null, client.id);
}

application.onDisconnect = function(client)
{
   //Get a lock because we might do 2 setProperty calls 
   //and we want only onSync to get triggered
   this.users_so.lock();

      //If the user is talking to someone, clean the other user's talkingTo field.
      var obj = this.users_so.getProperty(client.id);
      if (obj.talkingTo != null) {
         var otherUser = this.users_so.getProperty(obj.talkingTo);
         otherUser.talkingTo = null;
         this.users_so.setProperty(obj.talkingTo, otherUser);
      }

      //Clean the slot for the client that just left.
      this.users_so.setProperty(client.id, null);

   //Now the onSync will get triggered on the remaining clients
   this.users_so.unlock();
}

Save this code in a file called main.asc in a folder called central_vchat (I like to keep my application folder names all lowercase) under your Flash Communication Server applications folder.

The Client Side: Building the Application

The vChat application is nothing but a help page and a pod launcher, so it's possibly the easiest Central application you'll ever build.

Open Flash MX or Flash MX 2004 and create a new document, with a Stage size of 500 x 400 pixels. Use all the assets you need to make it look the way you want and add an Open vChat text field, with an Icon Button component next to it (get the component from the Central Components panel). Call the Icon Button component fShowPod and, in the parameters, choose icon_toss-to from the Built-In Icon menu.

Save the file as app.fla in a folder of your choice.

Because I like to keep my ActionScript code in a separate file, I created an app.as file right next to the app.fla I just created, and added #include "app.as" in the first frame of my movie's Timeline. You could also just paste the following code in the first frame within the FLA.

Either way, here's the whole ActionScript code:

//Central Methods
function getMinimumSize() { 
   return {width:500, height:400};
}
function getMaximumSize() {
   return {width: 500, height:400};
}
onActivate = function(shell, appId, shellId, baseTabIndex, appData) { 
   gShell = shell;
}
//Icon Button Handler
fShowPod.onRelease = function()
{
   var shownPods = gShell.getViewedPods();
   if (shownPods.length == 0) {
      var pods = gShell.getPods();
      gShell.viewPod(pods[0].id);
   }
}
// let the Central shell know we're loaded
// the shell will call us back soon with an onActivate
Central.initApplication(this, this);

stop(); 

All this code does is tell Central that the application is 500 pixels wide and 400 pixels high, and that it shouldn't resize. You define an onActivate method to save a reference of the Central shell in a gShell global variable. You use this reference in the fShowPod.onRelease function, which shows a pod only if the pod for this application doesn't already appear.

The last bit of Central magic you need to do is tell Central that you're alive by calling Central.initApplication.

That's all for this vChat application. As I said, it's very basic. Feel free to expand it at will.

The Client Side: Building the Pod

The interesting client-side code is in the Central pod that comes with the application.

In Flash MX or Flash MX 2004, create a new pod.fla file and make its Stage size 160 x 160 pixels. Create a Timeline like the one in Figure 2.

The Timeline for the vChat Pod

Figure 2. The Timeline for the vChat Pod

Let's start building the application, one screen at the time. In the login layer, add two Text Input Field components from the Central Components panel and call them room_txt and name_txt. In the label property, type Room and Login and set the Is Required flag to true on both. Now add a Push Button component (always from the Central Components panel, of course) and call it login_pb. Give it the label Login and the Click Handler doLogin.

Hide and lock the login layer and move to the list layer. Add a Push Button component to the top left of the Stage, call it vChat_pb, give it the label vChat and the doVChat Click Handler. Now add a List Box component and call it users_lb. Give it the Change Handler onListClick.

That's all you need for the list layer so hide it, lock it, and move to the video layer. Create a new video from the Library menu and drag two instances of it to the Stage. Make one of them big and the other one small, placed on top of the first. Call the big video videoIn and the small video videoOut. Draw a black rectangle around the videoOut video box and add another Push Button component to the Stage. Call it done_pb and give it the Done label and the Click Handler doDone.

Now, in the actions layer, either do #include "pod.as" or type in the code that appears in the snippets from here to the end of this section. Because there's a lot of code in this pod, I'll go through it one function at the time.

First you define an onActivate method:

//Central calls this when the pod is opened
function onActivate(dock, podid, viewerId, position, baseTabIndex, data)
{
   showScreen("login");

   //Global variables
   gServerName = "yourserver.com";
   gAppName = "central_vchat";

   this.gConsole = dock;

   //Local table of the users I know
   this.usersIKnow = new Object();

   //Get the local Shared Object (we save the last room and username used in it)
   this.localSO = SharedObject.getLocal("vChat");
   if (this.localSO.data.room == undefined) {
      this.localSO.data.room = "fun";
      this.localSO.data.userName = "";
   }
   //Populate UI
   this.room_txt.setValue(this.localSO.data.room);
   this.name_txt.setValue(this.localSO.data.userName);
}

This is the first method that Central calls on this pod. You define some global variables, save a reference to the console (you'll need it to pop up notifications), create a usersIKnow table (you'll use it later), and get a local shared object, in which you save the last room and username that the user selects. You then populate the login screen UI with the values retrieved from the local shared object.

Next you define an onDeactivate method:
//Central calls this when the pod is closed
function onDeactivate()
{
   //Close everything
   videoOut.clear();
   nsOut.close();
   videoIn.clear();
   nsIn.close();
   attachAudio(null);
   connectToFlashCom(false); //Disconnect
   showScreen("login");
}

Whenever a user closes the pod, the onDeactivate method is called by Central. In it, you close all streams (in case you were in the middle of a vChat) and disconnect from Flash Communication Server. This triggers an onDisconnect on the server side (see the code above), which cleans up the user's shared object.

Next you define all the necessary UI handlers, starting with doLogin:


//login_pb Click Handler
function doLogin() {
   if (this.login_pb.getLabel() == "Login") {
      //Save room and login in localSO
      this.localSO.data.room = this.room_txt.getValue();
      this.localSO.data.userName = name_txt.getValue();

      //If successful, it will showScreen("list") and populate it
      connectToFlashCom(true);
   } else
      connectToFlashCom(false); //Disconnect
}

Whenever a user clicks Login, you save the room and username in the local shared object (for next time) and connect to Flash Communication Server. If the button label says Logout, you disconnect from the server instead.

The two button handlers below are invoked whenever the user clicks the vChat button to initiate a vChat or clicks the Done button to finish it. The doVChat function sets a flag so you won't pop up a notification when onSync comes around (you'll see what I mean in a minute). Then you set the talkingTo member of your own slot and of the person you want to talk to (the one that's selected in the users_lb list box). This triggers an onSync on all clients, including yourself:

//vChat_pb Click Handler
function doVChat() {
   this.initiator = true; //Don't trigger an alert, I initiated this vChat

   //This will trigger an onSync/onSlotChanged on all clients
   this.so.data[this.users_lb.getSelectedItem().data].talkingTo = this.myID; //They're talking to me 
   this.so.data[this.myID].talkingTo = this.users_lb.getSelectedItem().data; //I'm talking to them 
}

//done_pb Click Handler
function doDone() {
   //This will trigger an onSync/onSlotChanged on all clients
   this.so.data[this.so.data[this.myID].talkingTo].talkingTo = null;
   this.so.data[this.myID].talkingTo = null;
}

The two methods below are pretty self-explanatory. The onListClick handler disables the vChat button if you selected yourself or someone who's already talking with someone else. The showScreen method is how you go from one screen to the other; it just sets the _visible property of each element on the Stage:

//users_lb Change Handler
function onListClick() {
   //You can't initiate a vChat with yourself or with
   //someone who's already chatting with someone else.
   var selID = this.users_lb.getSelectedItem().data;
   this.vChat_pb.setEnabled((selID != this.myID) && (this.so.data[selID].talkingTo == null));
}

//Changes the UI: name can be ["login" | "vchat" | "list"]
function showScreen(name) {
   this.name_txt._visible = (name == "login");
   this.room_txt._visible = (name == "login");

   this.login_pb.setLabel((name == "login") ? "Login" : "Logout");
   this.login_pb._y = (name == "login") ? 100 : 0;
   this.login_pb._visible = (name != "vchat");

   this.users_lb._visible = (name == "list");
   this.vChat_pb._visible = (name == "list");

   this.videoIn._visible = (name == "vchat");
   this.videoOut._visible = (name == "vchat");
   this.done_pb._visible = (name == "vchat");
   this.square_mc._visible = (name == "vchat");
}

The code below executes as soon as the pod loads (even before onActivate). All you do is define NetConnection and attach two methods to it. As you saw in the section on the server-side code, as soon as a connection to a client is accepted you call setID on the client to tell it what ID the server assigns to it. The client shouldn't be doing anything before this call arrives, so in onStatus don't check for NetConnection.Connect.Success. Instead, check for the opposite: If something goes wrong (the connection is closed or rejected or fails) then you just show the login screen again. The setID method is called right after a successful connection is established. After you save your unique ID in the myID variable, you show the user list screen and connect the shared object to populate the list:

//Create a NetConnection
nc = new NetConnection();
nc.mc = this;
nc.onStatus = function(info) {
   if (info.code != "NetConnection.Connect.Success")
      showScreen("login"); //Back to login screen if the connection is closed/rejected/failed.
}
nc.setID = function(id) { //Called by the server
   this.mc.myID = id;
   showScreen("list");
   connectSO();
}

The connectSO function below connects this client to the user's remote shared object and defines an onSync to it. (This is a small variation of my favourite onSync, which I use all the time. For more information about it, see my blog entry about it.) The onSync calls updateList (which just populates the user list) on the first onSync invocation, and then onSlotChanged (whenever a new user is created or a user starts or stops a vChat), or onSlotDeleted (whenever a user disconnects):

//Called by the nc.setID
function connectSO() {
   //Get the users Shared Object and attach my favourite onSync to it.
   this.so = SharedObject.getRemote("users", nc.uri, false);
   this.so.mc = this;
   this.so.firstTime = true;
   this.so.onSync = function(list) {
      if (this.firstTime) {
         this.firstTime = false;
         this.mc.updateList(); //Only update the list, skip the notification
         return;
      }
      for (var k in list) {
         if ((list[k].code == "change") || (list[k].code == "success"))
            this.mc.onSlotChanged(list[k].name); //This will pop-up a notification
         else if (list[k].code == "delete")
            this.mc.onSlotDeleted(list[k].name); //This will pop-up a notification
      }
   }
   this.so.connect(nc); //This will trigger an onSync
}

The onSlotChanged function is the hardest function you'll write, so look at it carefully:

//Called by onSync whenever a new user is created or a user starts or stops a vChat
this.onSlotChanged = function(id) {
   if (!this.usersIKnow[id]) { //User is new to me

      if (id != this.myID) { //Don't display a "user is connected" notice for myself.
         var notice = new Object();
         notice.name = this.so.data[id].name +" is connected";
         notice.description = this.so.data[id].name+" connected to "+this.localSO.data.userName;
         notice.timeout = 5;
         notice.alert = true;
         notice.engageString = "";
         this.gConsole.addNotice(notice);
      }

      //Save the name in the local table.
      this.usersIKnow[id] = this.so.data[id].name;
   }

   if (id == this.myID) { //It's myself

      if (this.so.data[this.myID].talkingTo != null) {
         //This means I either started a vChat or someone else wants to chat with me.
         showScreen("vchat");

         if (this.initiator)
            this.initiator = false;
         else {
            //Someone else initiated this vChat. Get my attention.
            var notice = new Object();
            notice.name = this.so.data[this.so.data[this.myID].talkingTo].name +" started a vChat with you";
            notice.description = this.so.data[this.so.data[this.myID].talkingTo].name +" started a vChat with you";
            notice.timeout = 10;
            notice.alert = true;
            notice.engageString = "";
            this.gConsole.addNotice(notice);
         }

         //Start receiving their stream
         nsIn = new NetStream(nc);
         videoIn.attachVideo(nsIn);
         attachAudio(nsIn);
         nsIn.play("user"+this.so.data[this.myID].talkingTo);

         //Start publishing my stream
         myCam = Camera.get();
         myCam.setMode(240,240,15);
         myCam.setKeyFrameInterval(30);
         myMic = Microphone.get();
         myMic.setRate(22);
         videoOut.attachVideo(Camera.get());
         nsOut = new NetStream(nc);
         nsOut.attachVideo(Camera.get());
         nsOut.attachAudio(Microphone.get());
         nsOut.publish("user"+this.myID);
      } else {
         //Either of us clicked on "Done"
         videoOut.clear();
         nsOut.close();
         videoIn.clear();
         nsIn.close();
         attachAudio(null);

         showScreen("list");
      }
   }

   //Update the list
   this.updateList();
}

Here's what it all means. First you check whether or not the slot is new to this client. The code does this by checking the local usersIKnow table. If it's a new user, and it's not yourself, you add a "UserX is connected" notice, which automatically disappears in five seconds—just as any IM client does. Then you save the username in the usersIKnow table so that the next time there's a change to that user's slot, you don't display another "UserX is connected" alert.

Moving on. If the slot that's changed is yourself, it could mean one of four things:

  1. You started a vChat with someone
  2. Someone else started a vChat with you
  3. You just connected
  4. Your vChat is over (either you or the other person clicked Done)

If the talkingTo member of your slot is not null, it's either case 1 or 2. If the initiator flag is set, you're in case 1 and you don't put up a notice. Otherwise, it's case 2 so this pod needs to attract your attention. This happens by popping up a Central notification for 10 seconds.

After that, you go to the vChat screen and publish a video and audio stream (with the name "user"+this.myID). You also play the stream of the other person you're "vChatting" with. Using the ID as part of the stream name makes it all easy!

If the talkingTo member is null, then it's case 3 or 4. Either way, you stop the streaming. (If it's case 3, nothing was streaming, but closing a closed stream doesn't hurt anything.) And then you go back to the list screen (you might be on it already).

Finally, you update the user list (remember that every client does this because every client gets an onSync):

//Called by the onSync whenever a user leaves
this.onSlotDeleted = function(id) {

   //Add a notice (note how we get the data from the
   //local usersIKnow table, used as a cache. We can't use
   //the Shared Object slot contents because it's too late!)
   var notice = new Object();
   notice.name = this.usersIKnow[id] +" left";
   notice.description = this.usersIKnow[id] +" left";
   notice.timeout = 5;
   notice.alert = true;
   notice.engageString = "";
   this.gConsole.addNotice(notice);

   //Delete from local table
   delete this.usersIKnow[id];

   //Update the list
   this.updateList();
}

The onSlotDeleted function gets called whenever someone else disconnects from the application—because they close the pod, close Central, unplug their network cable, or whatnot. In this case you add a regular IM-style notification, saying that the user left. Notice that to display the name of the user who just left you have to get it from the usersIKnow table. Looking at the slot in the shared object returns null because the slot has already been deleted on the server side! After displaying the notification you delete the slot from the local usersIKnow cache and repopulate the user list:

//Updates the user list
this.updateList = function() {
   //This implementation is not scalable, but it will do for this tutorial
   this.users_lb.removeAll();
   for (var i in this.so.data) {
      if (this.so.data[i].talkingTo != null) //They're in the middle of a vChat
         this.users_lb.addItem(this.so.data[i].name+" (talking to "+this.so.data[this.so.data[i].talkingTo].name+")", i);
      else
         this.users_lb.addItem(this.so.data[i].name, i);
   }
}

The above function is called by onSync, onSlotChanged, and onSlotDeleted. It populates the users_lb list box with the names of the users connected to the application and it appends "(talking to xxx)" for those users who are in the middle of a vChat. It also adds their ID as a data field (so that the doVChat and the onListClick handlers can do their job well).

Hang tight, we're almost there. All you have to do now is define the connectToFlashCom function, which either connects you to the Flash Communication Server or disconnects you from it:

//Utility method: strips a char from a string.
function removeChar(char,str) {
   var newStr = "";
   while (str.indexOf(char) != -1) {
      newStr = str.substring(0, str.indexOf(char)) + str.substring(str.indexOf(char)+1);
      str = newStr;
   }
   return str;
}

//Connects or disconnects to the Flash Communication Server
function connectToFlashCom(bool) {
   if (bool) {
      var roomName = this.localSO.data.room.toLowerCase(); //Cleans up the room name
      roomName = removeChar(" ",roomName);
      roomName = removeChar("/",roomName);
      nc.connect("rtmp://"+gServerName+"/"+gAppName+"/"+roomName, this.localSO.data.userName);
   } else
      nc.close();
}

	

First you define a little removeChar utility method to strip out illegal application instance characters from whatever the user typed in the room text field. The connectToFlashCom function cleans up the room_txt text field (its value was saved in the local shared object during the doLogin function) and uses it as an application instance name. This allows you to have multiple rooms on the same server. You also pass the username to the connect call so that the server side can create a slot for you in the user's shared object. If the bool parameter is false, you just close the connection. This triggers an onStatus with info.code == "NetConnection.Connect.Closed", which takes the UI back to the login screen.

One more line you can't forget!

//Tell Central we're a Pod. This will trigger onActivate
Central.initPod( this, this );

This tells Central that you're a pod and you're alive and kicking. Central responds by calling onActivate on you (which you defined first).

That's all there is to it! It wasn't too much, was it?

Save your file, package it in a product (look at the Central SDK documentation on how to do this), and start vChatting with your friends!

Lessons Learned

In this article I showed you Central code as much as I gave you some Flash Communication Server tricks. If you remove the notifications, this could be a pretty cool regular Flash Communication Server application, but Central takes it "to the next level."

Here are a few lessons I hope you take away from this tutorial:

  • Central provides you with things that were impossible to do before in the Flash world, such as easy distribution and notifications.
  • With Flash Communication Server you can do the following:
    • Assign unique IDs for your users on the server side
    • Have a smart onSync method
    • Save some data in a local client-side cache (the usersIKnow method)
    • Define an onDisconnect method on the server side (people don't always leave "politely")
    • Disable some UI if you want to limit the chat to one-to-one (the vChat button)

Consider this tutorial as a starting point. You should be able to expand it into a full-fledged application with all the bells and whistles you can muster.

For instance, you could add an option to allow text chat instead of video chat (for those who don't have a camera), or maybe just audio chat (for those who are shy). You could also make the application page into much more than just a simple help page.

If you have trouble deploying your Flash Communication Server application or your Central application and pod, refer to the documentation both on the Macromedia website and on the Central SDK. These manuals are really well done.


About the author

Giacomo "Peldi" Guilizzoni (aka peldi.com) is a software developer for Macromedia working on Breeze Live. He maintains a Flash Communication Server blog at peldi.com/blog/ and often writes for the Macromedia Developer Center. His grandparents do not understand a single word of this article but nonetheless think it's "neat." ;)